package smlab.media.FLVPlayer.view.state
{
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLRequest;
	import flash.system.LoaderContext;
	import flash.system.SecurityDomain;
	import flash.text.TextField;
	
	import smlab.media.FLVPlayer.CoreGlobal;
	import smlab.media.FLVPlayer.events.StateEvent;
	import smlab.utils.PopUpUtils;
	import smlab.view.state.Container_SM;
	
	/**
	 * 加载场景
	 * @author simon
	 * 
	 */
	public class LoadingState extends Container_SM
	{
		
		public function LoadingState()
		{
			super();
		}
		
		override public function initialize():void{
			
			CoreGlobal.infoTxt=new TextField;
			CoreGlobal.infoTxt.selectable=false;
			CoreGlobal.infoTxt.mouseEnabled=false;
			CoreGlobal.infoTxt.text="正在加载播放器组件……";
			CoreGlobal.infoTxt.textColor=0xffffff;
			centerInfoTxt();
			CoreGlobal.stage.addChild(CoreGlobal.infoTxt);
			
			this.initialized=true;
			dispatchEvent(new StateEvent(StateEvent.STATE_INITIALIZED));
		}
		
		override public function start():void{
			var l:Loader=new Loader;
			l.contentLoaderInfo.addEventListener(Event.COMPLETE,onSkinLoaded);
            l.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
            l.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressHandler);
            l.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
            l.load(new URLRequest(CoreGlobal.playerSkinURL),new LoaderContext(false,CoreGlobal.appDomain));
		}
		
		override public function sleep():void{
			CoreGlobal.infoTxt.text='';
		}
		
		private function onSkinLoaded(e:Event):void{
			CoreGlobal.infoTxt.text='播放器组件加载完成！';
			centerInfoTxt();
			CoreGlobal.stateEventDispatcher.dispatchEvent(new StateEvent(StateEvent.SWITCH_TO_AD_STATE));
		}
		
		private function ioErrorHandler(e:IOErrorEvent):void {
			CoreGlobal.infoTxt.text='无法加载播放器组件，请检查链接！';
			centerInfoTxt();
		}
		
		private function progressHandler(e:ProgressEvent):void {
			CoreGlobal.infoTxt.text='正在加载播放器组件：'+int(e.bytesLoaded/e.bytesTotal*100)+'%';
			centerInfoTxt();
		}
		
		private function securityErrorHandler(e:SecurityErrorEvent):void {
			CoreGlobal.infoTxt.text='加载播放器界面时遇到安全沙箱问题！';
			centerInfoTxt();
		}
		
		/**
		 * 使文本居中
		 * 
		 */
		private function centerInfoTxt():void{
			CoreGlobal.infoTxt.width=CoreGlobal.infoTxt.textWidth+5;
			PopUpUtils.centerInStage(CoreGlobal.infoTxt);
		}
			
	}
}